package com.wjd.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjd.common.utils.PageUtils;
import com.wjd.common.utils.Query;
import com.wjd.gulimall.product.dao.BrandDao;
import com.wjd.gulimall.product.entity.BrandEntity;
import com.wjd.gulimall.product.service.BrandService;
import com.wjd.gulimall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Lazy
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        LambdaQueryWrapper<BrandEntity> query = new LambdaQueryWrapper<BrandEntity>()
                .and(wrapper -> wrapper.eq(BrandEntity::getBrandId, key).or().like(BrandEntity::getName, key));
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params), query
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void updateBrand(BrandEntity brand) {
        // 1. 更新品牌信息
        this.updateById(brand);
        // 2. 更新关联表中的冗余品牌名称
        if (StringUtils.isNotBlank(brand.getName())) {
            categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());
        }
    }

}